package com.wkn.wknAdmin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.wkn.wknAdmin.entity.Menu;
import com.wkn.wknAdmin.entity.RoleMenu;
import com.wkn.wknAdmin.mapper.MenuMapper;
import com.wkn.wknAdmin.mapper.RoleMenuMapper;
import com.wkn.wknAdmin.service.MenuService;
import com.wkn.wknAdmin.service.RoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title:
 * @Description:
 * @Author: WKN
 * CreateDate: 2022/8/15 10:23
 */
@Service
public class RoleMenuServiceImpl implements RoleMenuService {


    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public int insert(RoleMenu roleMenu) {
        return roleMenuMapper.insert(roleMenu);
    }

    @Transactional                      // 事务注解，保证同时成功或者都不成功
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
        // 先删除和当前角色绑定的所以菜单
        roleMenuMapper.deleteByRoleId(roleId);

        //然后进行添加
        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            Menu menu = menuMapper.getOneById(menuId);
            if(menu.getPid() != null  && !menuIdsCopy.contains(menu.getPid())){   // 表示二级菜单 并且传过来的id数组没有他的父级
                // 需要加上父级id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }

            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }
    }


    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMenuMapper.getRoleMenu(roleId);
    }
}
